package dao;

import dao.html.HtmlParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Timur Yarosh
 *         Date: 13.06.13
 *         Time: 11:55
 */
public class WebScannerDao {
    private final Pattern hostAddrPattern;
    private final String HOST;

    public WebScannerDao(String HOST) {
        this.HOST = HOST;
        hostAddrPattern = Pattern.compile("http.*//(.+)/");
    }

    public List<String> fetchExternalLinks() throws IOException {
        List<String> externalLinks = new ArrayList<String>();
        List<String> allLinks = fetchAllLinks();
        for (String link : allLinks) {
            if (!isInternalLink(link)) {
                externalLinks.add(link);
            }
        }
        return externalLinks;
    }

    public List<String> fetchInternalLinks() throws IOException {
        List<String> internalLinks = new ArrayList<String>();
        List<String> allLinks = fetchAllLinks();
        for (String link : allLinks) {
            if (isInternalLink(link)) {
                internalLinks.add(link);
            }
        }
        return internalLinks;
    }

    private boolean isInternalLink(String link) {
        String hostAddr = parseHostAddress(HOST);
        boolean internal = false;
        if ((link.startsWith("/")) || (link.startsWith("../") || link.contains(hostAddr))) {
            internal = true;
        }
        return internal;
    }

    private String parseHostAddress(String host) {
        String hostaddr = null;
        Matcher matcher = hostAddrPattern.matcher(host);
        if (matcher.find()) {
            hostaddr = matcher.group(1);
        }
        return hostaddr;
    }

    private List<String> fetchAllLinks() throws IOException {
        return new ArrayList<String>(new HtmlParser(this.HOST).getLinks());
    }


}
